package com.student_system.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.student_system.system.entity.SysRoleMenu;
import com.student_system.system.mapper.SysRoleMenuMapper;
import com.student_system.system.service.ISysRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ljy
 * @since 2025-05-14
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {
    @Override
    public List<Integer> getMenuIdsByRoleId(Long roleId) {  // 修改返回值类型为List<Integer>
        QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        List<SysRoleMenu> roleMenus = this.list(queryWrapper);

        return roleMenus.stream()
                .map(roleMenu -> roleMenu.getMenuId().intValue())  // 添加强制类型转换
                .collect(Collectors.toList());
    }

    @Override
    public void assignMenusToRole(Long roleId, List<Integer> menuIds) {
        // 先删除该角色的所有菜单
        QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        this.remove(queryWrapper);
        // 再插入新的菜单
        if (menuIds != null && !menuIds.isEmpty()) {
            List<SysRoleMenu> roleMenus = menuIds.stream()
                    .map(menuId -> {
                        SysRoleMenu roleMenu = new SysRoleMenu();
                        roleMenu.setRoleId(roleId.intValue());  // Long转Integer
                        roleMenu.setMenuId(menuId);            // 保持Integer类型
                        return roleMenu;
                    }).collect(Collectors.toList());
            baseMapper.insert(roleMenus);
        }
    }
}
